package com.neulogistics.core.substation.api.application.query;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neulogistics.core.substation.api.application.converter.TaskOrderPOVMConverter;
import com.neulogistics.core.substation.api.application.converter.TaskOrderQueryPOConverter;
import com.neulogistics.core.substation.api.application.viewmodel.TaskOrderViewModel;
import com.neulogistics.core.substation.infrastructure.persistence.orm.po.TaskOrderPO;
import com.neulogistics.core.substation.infrastructure.persistence.orm.service.ITaskOrderPOService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class TaskOrderQueryService implements ITaskOrderQueryService {
    @Resource
    ITaskOrderPOService taskOrderPOService;

    @Override
    public TaskOrderViewModel getById(Long id) {
        TaskOrderPO taskOrderPO = taskOrderPOService.getById(id);
        TaskOrderViewModel taskOrderViewModel = TaskOrderPOVMConverter.POToVM(taskOrderPO);
        return taskOrderViewModel;
    }

    @Override
    public Page<TaskOrderViewModel> page(TaskOrderQuery taskOrderQuery) {
        // 取出条件
        TaskOrderPO taskOrderPOQuery = TaskOrderQueryPOConverter.queryToPO(taskOrderQuery);
        long current = taskOrderQuery.getPageNum();
        long pageSize = taskOrderQuery.getPageSize();

        // 查询
        QueryWrapper<TaskOrderPO> queryWrapper = new QueryWrapper<>(taskOrderPOQuery);

        // 构造状态条件
        if(taskOrderQuery.taskStatus != null && taskOrderQuery.taskStatus.length >= 1 && taskOrderQuery.taskStatus[0] != -1){
            ArrayList<Integer> status = new ArrayList<>(taskOrderQuery.taskStatus.length);
            for (int i : taskOrderQuery.taskStatus){
                status.add(i);
            }
            queryWrapper.in("task_status", status);
        }

        // 构造配送员条件
        if(taskOrderQuery.courierId != null){
            queryWrapper.eq("JSON_EXTRACT(courier_info, '$.courierId')", taskOrderQuery.courierId);
        }

        Page<TaskOrderPO> page = taskOrderPOService.page(new Page<>(current, pageSize), queryWrapper);



        // 构造结果
        Page<TaskOrderViewModel> viewModelPage = new Page<>(current, pageSize);
        List<TaskOrderViewModel> viewModelList = page.getRecords().stream()
                .map(TaskOrderPOVMConverter::POToVM).collect(Collectors.toList());
        viewModelPage.setRecords(viewModelList);
        viewModelPage.setTotal(page.getTotal());

        return viewModelPage;
    }
}
